<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/29/029
 * Time: 11:08
 */

namespace app\api\model;


use app\api\service\Token;
use app\api\model\Address as AddressModel;
use app\api\model\Product as ProductModel;
use app\api\model\Attribute as AttributeModel;
use app\api\model\AttrValue as AttrValueModel;
use app\api\model\PatternMaster as PatternMasterModel;
use app\api\model\MemberFigureMeasureData as MemberFigureMeasureDataModel;
use app\lib\exception\AddressException;
use app\lib\exception\OrderException;
use app\lib\exception\PatternMasterException;
use app\lib\exception\ProductException;
use app\api\model\Member as MemberModel;
use app\api\service\Order as OrderService;
use app\api\model\OrderFigureMeasureData as OrderFigureMeasureDataModel;
use app\api\model\OrderProduct as OrderProductModel;
use think\Db;
use think\Exception;
use Map\Map;

class Order extends BaseModel {

    protected $hidden = ['update_time','sub_account_status', 'express_subscription'];

    /**
     * 订单用户
     * @return \think\model\relation\belongsTo
     */
    public function orderMember() {
        return $this->belongsTo('Member');
    }

    /**
     * 订单量体师
     * @return \think\model\relation\belongsTo
     */
    public function orderPatternMaster() {
        return $this->belongsTo('PatternMaster');
    }

    /**
     * 订单产品
     * @return \think\model\relation\hasOne
     */
    public function orderProduct() {
        return $this->hasOne('OrderProduct');
    }

    /**
     * 订单量体数据
     * @return \think\model\relation\HasOne
     */
    public function orderFigureMeasure() {
        return $this->hasOne('OrderFigureMeasureData');
    }

    /**
     * 订单售后
     * @return \think\model\relation\hasOne
     */
    public function orderAfterSale() {
        return $this->hasOne('OrderAfterSale');
    }

    /**
     * 获取用户订单列表
     * @param $status
     * @param $comment_status
     * @param $is_pattern_master
     * @return \think\Paginator
     * @throws PatternMasterException
     */
    public static function getMemberOrderList($status, $comment_status, $is_pattern_master) {

        $uid = Token::getCurrentUid();

        if ($status > 0) {
            $where[] = ['status', '=', $status];
            if ($status == 6) {
                $where[] = ['comment_status', '=', 0];
                $where[] = ['after_sale_status', 'in', '0, 2'];
            }
        }

        if ($comment_status > 0) {
            $where[] = ['comment_status', '=', $comment_status];
        }

        if ($is_pattern_master) {
            $patternMaster = PatternMasterModel::get(['member_id' => $uid, 'status' => 2]); // 获取量体师信息
            if (!$patternMaster) {
                throw new PatternMasterException([
                    'msg' => '您还没有申请量体师，或者申请还没有通过',
                    'errorCode' => 13001
                ]);
            }
            $where[] = ['pattern_master_id', '=', $patternMaster['id']];
            $where[] = ['status', '>', 2]; // 只显示接单之后的订单
        } else {
            $where[] = ['member_id', '=', $uid];
        }

        $orders = self::with('orderProduct.product.brand')->where($where)->order('id desc')->paginate(5, true);
        foreach ($orders as &$order) {
            $order->order_product->product->visible(['type', 'brand']);
            $order->status_text = self::get_order_status_text($order->status, $order->after_sale_status, $order->comment_status);
        }
        return $orders;
    }

    /**
     * 获取量体订单状态信息
     * @param $status
     * @param $after_sale_status
     * @param $comment_status
     * @return mixed|string
     */
    public static function get_order_status_text($status, $after_sale_status, $comment_status) {
        $status_array = ['', '待付款', '已付款', '量体师已接单', '量体师已确认', '已发货', '已签收', '完成', '已关闭', 99 => '已发货'];
        if ($status == 6 || $status == 5) {
            if ($after_sale_status == 1) {
                return '申请售后';
            }

            if ($after_sale_status == 2) {
                return '售后处理中';
            }

            if ($comment_status == 0) {
                return '待评价';
            }
        }
        return $status_array[$status];
    }

    /**
     * 确认订单数据
     * @param $id
     * @param $product_attr
     * @return array
     * @throws ProductException
     */
    public static function bookingQuantityBody($id, $product_attr) {

        $uid = Token::getCurrentUid();

        $address = AddressModel::getDefaultAddressInfo($uid);

        $product = ProductModel::getProductInfo($id, 1);
        if (!$product) {
            throw new ProductException();
        }
        $product->visible(['id', 'name', 'price', 'thumb', 'brand', 'category']);

        $attr = [];
        if ($product_attr) {
            $attr = explode(',', $product_attr);
            $attr_ids = [];
            $attr_val_ids = [];
            foreach ($attr as $k => $v) {
                $a = explode('-', $v);
                $attr_ids[] = $a[0];
                $attr_val_ids[] = $a[1];
            }

            $attr = AttributeModel::getAttrByIds($attr_ids);
            $attr_value = AttrValueModel::getAttrValueByIds($attr_val_ids);

            foreach ($attr as $key => $val) {
                $attr_v = [];
                foreach ($attr_value as $k => $v) {
                    if ($v['attribute_id'] == $val['id']) {
                        $attr_v[] = $v;
                    }
                }
                if ($attr_v) {
                    $val['value'] = $attr_v;
                }
                $attr[$key] = $val;
            }
        }

        // + ------- 获取最近量体数据  -------- + //
        $last_order_figure_measure = MemberFigureMeasureDataModel::get(['member_id' => $uid]);

        return [
            'address' => $address,
            'product' => $product,
            'attr' => $attr,
            'last_order_figure_measure' => $last_order_figure_measure,
            'order' => [
                'price' => $product['price']
            ]
        ];
    }

    /**
     * 创建订单
     * @param $params
     * @return static
     * @throws AddressException
     * @throws OrderException
     */
    public static function createOrder($params) {
//$id, $address_id, $source, $attr, $figure_measure_data_is_again
        $uid = Token::getCurrentUid();

        $address = AddressModel::getAddressInfoById($params['address_id'], $uid);
        if (!$address) {
            throw new AddressException();
        }

        //根据地址获取经纬度
        $lng_lat = Map::getLngLat($address['region_province']['region_name'] . $address['region_city']['region_name'] . $address['region_area']['region_name'] . $address['address']);

        $attr = isset($params['attr']) ? $params['attr'] : '';
        $quantity_order_data = self::bookingQuantityBody($params['id'], $attr);

        // 获取下单用户信息
        $member = MemberModel::get(['id' => $uid]);

        Db::startTrans();
        try {
            // 组装订单数据
            $order_data = [
                'order_sn' => OrderService::makeOrderNo('LT'),
                'member_id' => $uid,
                'price' => $quantity_order_data['order']['price'],
                'consignee' => $address['linkman'],
                'mobile' => $address['mobile'],
                'province' => $address['region_province']['region_name'],
                'city' => $address['region_city']['region_name'],
                'area' => $address['region_area']['region_name'],
                'address' => $address['address'],
                'lat' => $lng_lat['result']['location']['lat'],
                'lng' => $lng_lat['result']['location']['lng'],
                'pattern_master_id' => $member['relevance_pattern_master_id'],
                'source' => $params['source']
            ];
            $order = self::create($order_data);

            if ($order) {
                if (isset($params['figure_measure_data_is_again']) && $params['figure_measure_data_is_again'] == 1) { // 使用上次量体数据
                    if ($quantity_order_data['last_order_figure_measure']) {
                        $order_figure_measure_data = $quantity_order_data['last_order_figure_measure'];
                        $order_figure_measure_data->hidden(['abdominal_girth']);
                        $order_figure_measure_data->order_id = $order['id'];
                        OrderFigureMeasureDataModel::create($order_figure_measure_data);
                    }
                }

                //组装订单产品数据
                $order_product_data = [
                    'order_id' => $order['id'],
                    'product_id' => $params['id'],
                    'name' => $quantity_order_data['product']['name'],
                    'price' => $quantity_order_data['product']['price'],
                    'thumb' => $quantity_order_data['product']['thumb'],
                    'num' => 1,
                    'attr' => json_encode($quantity_order_data['attr'])
                ];
                OrderProductModel::create($order_product_data);

                // 订单创建成功  推送通知
                OrderService::sendCreateOrderMsg($order_data);

                // 检查用户订单数量，如果是首次下单，需要发送微信消息
                OrderService::checkMemberOrderNum($uid, $member, $order_data);
            } else {
                throw new OrderException([
                    'msg' => '订单创建失败',
                    'errorCode' => 60001
                ]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new OrderException([
                'msg' => $e,
                'errorCode' => 60001
            ]);
        }

        return $order->id;
    }

    /**
     * 获取订单详情，支持量体师获取
     * @param $id
     * @param $is_pattern_master
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws OrderException
     * @throws PatternMasterException
     */
    public static function getOrderInfo($id, $is_pattern_master) {

        $uid = Token::getCurrentUid();

        if ($is_pattern_master) {
            $patternMaster = PatternMasterModel::get(['member_id' => $uid, 'status' => 2]); // 获取量体师信息
            if (!$patternMaster) {
                throw new PatternMasterException([
                    'msg' => '您还没有申请量体师，或者申请还没有通过',
                    'errorCode' => 13001
                ]);
            }
            $where = ['id' => $id, 'pattern_master_id' => $patternMaster['id']];
        } else {
            $where = ['id' => $id, 'member_id' => $uid];
        }

        $order = self::with(['orderProduct.product.brand', 'orderPatternMaster.patternMasterMember.memberRoleInfo'])->where($where)->find();

        if (!$order) {
            throw new OrderException();
        }

        $order['status_text']  =  self::get_order_status_text($order['status'], $order['after_sale_status'], $order['comment_status']);
        $order->order_product->product->visible(['type', 'brand']);
        if (isset($order->order_pattern_master) && $order->order_pattern_master) {
            $order->order_pattern_master->visible(['name', 'id', 'pattern_master_member'])
                ->pattern_master_member->visible(['member_role_info'])
                ->member_role_info->visible(['headimgurl']);
        }


        return $order;
    }

    /**
     * 根据ID删除定制订单11
     * @param $id
     * @return bool
     * @throws Exception
     * @throws OrderException
     */
    public static function deleteOrder($id) {
        $uid = Token::getCurrentUid();

        $order = self::get(['id' => $id, 'member_id' => $uid]);

        if (!$order) {
            throw new OrderException();
        }

        if ($order['status'] != 1) {
            throw new OrderException([
                'msg' => '订单状态异常，只有未付款订单可以删除',
                'errorCode' => 60002
            ]);
        }
        Db::startTrans();
        try {
            $order->orderProduct->delete();
            $order->delete();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
        return true;
    }

    /**
     * 确认收货
     * @param $id
     * @return false|int
     * @throws OrderException
     */
    public static function orderConfirmReceipt($id) {
        $uid = Token::getCurrentUid();

        $order = self::get(['id' => $id, 'member_id' => $uid]);

        if (!$order) {
            throw new OrderException();
        }

        if ($order['status'] != 5 && $order['status'] != 99) {
            throw new OrderException([
                'msg' => '订单状态异常，只有待收货订单可以确认收货',
                'errorCode' => 60002
            ]);
        }

        $rs = $order->save(['receipt_time' => time(), 'status' => 6]);
        return $rs;
    }

    /**
     * 获取物流信息
     * @param $express_sn
     * @return array
     */
    public static function expressInfo($express_sn) {

        $order = self::get(['express_sn' => $express_sn]);

        $data = OrderService::expressInfo($order, $express_sn, 'orderProduct');

        return $data;
    }

    /**
     * 获取用户定制订单数量，可指定状态
     * @param $uid
     * @param int $status
     * @return int|string
     */
    public static function getMemberOrderCount($uid, $status = 0) {
        $where[] = ['member_id' ,'=', $uid];
        if ($status > 0) {
            $where[] = ['status', '=',  $status];
            if ($status == 6) {
                $where[] = ['comment_status', '=', 0];
                $where[] = ['after_sale_status', 'in', '0, 2'];
            }
        }
        return self::where($where)->count();
    }
}